package ui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import build.BatchPack;


@SuppressWarnings("serial")
public class PackLauncher extends JFrame implements ActionListener{

	List<ProjectPanel> projectPanels=new ArrayList<ProjectPanel>();
	
	JScrollPane contentPane;
	
	Box contentBox=Box.createVerticalBox();
	
	JProgressBar progressBar=new JProgressBar();
	
	JButton batchButton=new JButton("生成");
	
	JCheckBox isBatchAdd=new JCheckBox("批量添加");
	
	JButton clearButton=new JButton("清除");
	
	public PackLauncher()
	{
		super("Android apk打包工具生成器  @author 13leaf");
		File[] projects=new File("projects").listFiles(new ProjectFileFilter());
		for(File projectFile :projects)
		{
			BatchPack pack=new BatchPack(projectFile.getAbsolutePath());
			ProjectPanel projectPanel=new ProjectPanel(pack, projectFile.getName());
			projectPanels.add(projectPanel);
			contentBox.add(projectPanel);
		}
		
		progressBar.setStringPainted(true);
		progressBar.setString("");
		
		contentPane=new JScrollPane(contentBox);
		add(progressBar,BorderLayout.NORTH);
		add(contentPane,BorderLayout.CENTER);
		
		JPanel bottomTools=new JPanel();
		bottomTools.add(isBatchAdd);
		bottomTools.add(batchButton); batchButton.addActionListener(this);
		bottomTools.add(clearButton); clearButton.addActionListener(this);
		
		add(bottomTools,BorderLayout.SOUTH);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(400,750);
		setLocation(200, 50);
		setVisible(true);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource()==clearButton)
		{
			for(ProjectPanel panel :projectPanels)
			{
				panel.init();
			}
		}
		
		if(e.getSource()==batchButton)
		{
		new Thread(){
			public void run() {
				//do batch work
				final StringBuilder results=new StringBuilder();

				progressBar.setIndeterminate(true);
				
				batchButton.setEnabled(false);//开始生成
				for(ProjectPanel projectPanel : projectPanels){
					if(projectPanel.wantBatch())
					{
						BatchPack batchPack=projectPanel.getProjectBatch();
						batchPack.setOnBatchListener(new BatchPack.onBatchListener() {
							@Override
							public void onTaskSuccess(BatchPack batch,Map<String,String> runValue) {
								results.append(batch.getAttributes().getProperty("projectName")+
										"-"+runValue+"生成成功!\n");
							}
							@Override
							public void onTaskFail(BatchPack batch,Map<String,String> runValue) {
								results.append(batch.getAttributes().getProperty("projectName"+
										"-"+runValue+"生成失败!\n"));
							}
						});
						batchPack.doBatch(projectPanel.getRunValues());
					}
				}
				
				progressBar.setString("生成完毕");
				progressBar.setIndeterminate(false);
				//end batch
				batchButton.setEnabled(true);
				JOptionPane.showMessageDialog(PackLauncher.this, results);
			}
		
		}.start();
		}
	}
	
	
	class ProjectFileFilter implements FileFilter
	{

		@Override
		public boolean accept(File pathname) {
			return pathname.getName().endsWith(".project");
		}
		
	}
	
	public static void main(String[] args) {
		new PackLauncher();
	}

}

@SuppressWarnings("serial")
class MacroPanel extends JPanel{
	
	JLabel[] macroNameLabels;
	JTextField[] macroTextValues;
	
	public MacroPanel(String... macroNames)
	{
		setBorder(BorderFactory.createEtchedBorder());
		
		macroNameLabels=new JLabel[macroNames.length];
		macroTextValues=new JTextField[macroNames.length];
		setLayout(new GridLayout(0, 3));
		for(int i=0;i<macroNames.length;i++)
		{
			String macroName=macroNames[i];
			JLabel macroNameLabel=new JLabel(macroName);
			add(macroNameLabel);
			add(new JLabel("="));
			JTextField macroTextValue=new JTextField();
			add(macroTextValue);
			//
			macroNameLabels[i]=macroNameLabel;
			macroTextValues[i]=macroTextValue;
		}
	}
	
	
	/**
	 * 取得MacroPanel当前的宏替换值
	 * @return
	 */
	public Map<String, String> getRunValue()
	{
		Map<String, String> value=new HashMap<String, String>();
		for(int i=0;i<macroNameLabels.length;i++)
		{
			if(macroTextValues[i].getText().trim().length()!=0)//跳过空字段
				value.put(macroNameLabels[i].getText(), macroTextValues[i].getText());
		}
		return value;
	}
}

@SuppressWarnings("serial")
class ProjectPanel extends JPanel{
	
	JCheckBox wantBatch=new JCheckBox();//勾选框，不选中则取消生成
	
	JLabel projectLabel=new JLabel();
	
	JButton buttonAdd=new JButton("+");//add macro
	
	BatchPack projectBatch;
	
	List<MacroPanel> macroPanels=new ArrayList<MacroPanel>();
	
	List<JButton> removeMacroButtons=new ArrayList<JButton>();
	
	Box contentBox=Box.createVerticalBox();//内容以纵向进行布局
	
	String[] macroNames;
	
	/**
	 * 此处的projectName特指projects目录下的*.project。如test.project时，该处显示名称为test
	 * @param batchPack
	 * @param projectName
	 */
	public ProjectPanel(BatchPack batchPack,String projectName)
	{
		projectBatch=batchPack;
		
		projectLabel.setText(projectName);
		
		setLayout(new BorderLayout());
		//init macroNames
		LinkedList<String> macroNameList=projectBatch.getMacros();
		macroNames=macroNameList.toArray(new String[macroNameList.size()]);
		
		JPanel titleBar=new JPanel();
		titleBar.add(wantBatch);wantBatch.setSelected(true);
		titleBar.add(projectLabel);
		titleBar.add(buttonAdd);
		add(titleBar,BorderLayout.NORTH);
		
		//init ui
		contentBox.setBorder(BorderFactory.createTitledBorder("批处理-"+projectName));
		add(contentBox,BorderLayout.CENTER);
		
		
//		addMacroPanel();
		init();
		//set listener
		buttonAdd.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				addMacroPanel();
			}
		});
	}
	
	/**
	 * 初始化
	 */
	public void init()
	{
		contentBox.removeAll();
		macroPanels.clear();
		removeMacroButtons.clear();
		addMacroPanel();
	}
	
	/**
	 * 是否选中要做Batch
	 * @return
	 */
	public boolean wantBatch()
	{
		return wantBatch.isSelected();
	}
	
	public BatchPack getProjectBatch()
	{
		return projectBatch;
	}

	/**
	 * 添加一个宏定义模板
	 */
	private void addMacroPanel() {
		MacroPanel macroPanel=new MacroPanel(macroNames);
		JButton removeButton=new JButton("-");
		contentBox.add(removeButton);
		contentBox.add(macroPanel);
		
		macroPanels.add(macroPanel);
		removeMacroButtons.add(removeButton);
		
		final int id=macroPanels.size()-1;
		//超懒的删除实现。。。就这样吧 = =!
		removeButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				removeMacroButtons.get(id).setVisible(false);
				macroPanels.get(id).setVisible(false);
			}
		});
		macroPanel.updateUI();
//		repaint(getBounds());
		//how to notify repaint??
		
	}
	
	/**
	 * 获取批处理的宏替换列表
	 * @return
	 */
	public List<Map<String, String>> getRunValues()
	{
		List<Map<String, String>> list=new ArrayList<Map<String,String>>();
		
		for(MacroPanel panel : macroPanels)
		{
			if(panel.isVisible())//不Visible的即被删除的。。很懒吧?
			{
				Map<String, String> runValue=panel.getRunValue();
				if(runValue.size()!=0)//仅取非空字段
					list.add(runValue);
			}
		}
		return list;
	}
	
}